using System;
using System.Collections.Generic;
using System.Linq;

namespace Prometheus.Binding.ReadOnly
{
    public class proBooleansMultiConverter : IMultiConverter
    {
        public proBooleanOperatorType OperatorType { get; set; }
        public bool DefaultValue { get; set; }

        #region IMultiConverter Members

        public object Convert(object[] values)
        {
            IEnumerable<bool> bools;
            try
            {
                bools = values.Select(v => (v is bool) && (bool) v).ToArray();
            }
            catch (InvalidCastException)
            {
                return DefaultValue;
            }

            bool result = DefaultValue;
            switch (OperatorType)
            {
                case proBooleanOperatorType.And:
                    if (!bools.Any()) return DefaultValue;
                    result = true;
                    foreach (bool b in bools)
                    {
                        result = result && b;
                    }
                    break;

                case proBooleanOperatorType.Or:
                    if (!bools.Any()) return DefaultValue;
                    result = false;
                    foreach (bool b in bools)
                    {
                        result = result || b;
                    }
                    break;
            }
            return result;
        }

        #endregion
    }
}